package com.piggy.logi.sys.api.utils;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.piggy.common.core.exception.GlobalException;
import com.piggy.logi.sys.api.utils.entity.ZhongYouResultEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 众油api工具类
 *
 * @author pc
 * @date 2024/01/15 13:59
 **/
@Component
public class ZhongYouApiUtil {

    private static final Logger log = LoggerFactory.getLogger(ZhongYouApiUtil.class);

    private static String url;

    @Value("${zhongYou.url: }")
    private void setUrl(String url) {
        ZhongYouApiUtil.url = url;
    }

//    public static void main(String[] args) {
//        ZhongYouApiUtil.url = "http://118.195.232.241/api/transportation/";
//        ZhongYouApiUtil.orderCallBack("1", "1", "1", "1", "1", "1", 1f, "1", "1", "1", "1");
//        ZhongYouApiUtil.orderChangeCallBack("1", "1", "1", "1");
//        ZhongYouApiUtil.orderStateChange("1", "1", "1", 1);
//        ZhongYouApiUtil.orderFinish("1", "1", "1", "1");
//    }

    /**
     * 物流平台调度好司机后，回调告诉众油平台
     *
     * @param pickupOrderNo    众油平台唯一订单id（以提货单号为唯一ID）
     * @param transId          物流平台唯一运单id
     * @param driverName       司机名称
     * @param driverMobile     司机手机号
     * @param driverIdCard     司机身份证号码
     * @param cardNo           车牌号码
     * @param count            数量(吨) 浮点数，精确到小数点后3位
     * @param strDate          日期例子： 2024-3-15 :12:24:35
     * @param supercargoName   押送人
     * @param supercargoId     押送人证件
     * @param supercargoMobile 押送人手机/电话
     * @author fengxy
     * @date 2024/01/15 14:06
     **/
    public static void orderCallBack(String pickupOrderNo, String transId, String driverName, String driverMobile,
                                     String driverIdCard, String cardNo, Float count, String strDate,
                                     String supercargoName, String supercargoId, String supercargoMobile) {
        long start = System.currentTimeMillis();
        log.info("运单【{}】物流平台已调度好司机，开始回调众油平台", transId);
        Map<String, Object> params = MapUtil.newHashMap();
        params.put("pickupOrderNo", pickupOrderNo);
        params.put("transId", transId);
        params.put("driverName", driverName);
        params.put("driverMobile", driverMobile);
        params.put("driverIdCard", driverIdCard);
        params.put("cardNo", cardNo);
        params.put("count", count);
        params.put("strDate", strDate);
        params.put("supercargoName", supercargoName);
        params.put("supercargoId", supercargoId);
        params.put("supercargoMobile", supercargoMobile);
        log.info("请求参数：{}", JSONUtil.toJsonStr(params));
        String responseStr = HttpUtil.post(url + "/orderCallBack", params);
        log.info("响应结果：{}", responseStr);
        if (StrUtil.isBlank(responseStr)) {
            log.error("回调众油平台异常，响应结果为空");
//            throw new GlobalException("回调众油平台异常，响应结果为空");
        }
        if (JSONUtil.isTypeJSON(responseStr)) {
            ZhongYouResultEntity<Object> result = JSON.parseObject(responseStr, new TypeReference<ZhongYouResultEntity<Object>>() {
            });
            if ("succ".equals(result.getMsg())) {
                log.info("回调成功，总用时：{}ms", System.currentTimeMillis() - start);
            } else {
                log.error("回调众油平台失败，失败原因：{}", result.getMsg());
//                throw new GlobalException(String.format("回调众油平台失败，失败原因：%s", result.getMsg()));
            }
        } else {
            log.error("回调众油平台返回结果格式异常");
        }
    }

    /**
     * 物流平台取消调度后，回调告诉众油平台
     *
     * @param pickupOrderNo 众油平台唯一订单id（以提货单号为唯一ID）
     * @param transId       物流平台唯一运单id
     * @param strDate       日期例子： 2024-3-15 :12:24:35
     * @param reason        取消原因，如：油车被盗，司机挂了
     * @author fengxy
     * @date 2024/01/15 14:06
     **/
    public static void orderChangeCallBack(String pickupOrderNo, String transId, String strDate, String reason) {
        long start = System.currentTimeMillis();
        log.info("运单【{}】有异常情况，开始回调众油平台取消调度", transId);
        Map<String, Object> params = MapUtil.newHashMap();
        params.put("pickupOrderNo", pickupOrderNo);
        params.put("transId", transId);
        params.put("strDate", strDate);
        params.put("reason", reason);
        log.info("请求参数：{}", JSONUtil.toJsonStr(params));
        String responseStr = HttpUtil.post(url + "/orderChangeCallBack", params);
        log.info("响应结果：{}", responseStr);
        if (StrUtil.isBlank(responseStr)) {
            log.error("回调众油平台异常，响应结果为空");
//            throw new GlobalException("回调众油平台异常，响应结果为空");
        }
        if (JSONUtil.isTypeJSON(responseStr)) {
            ZhongYouResultEntity<Object> result = JSON.parseObject(responseStr, new TypeReference<ZhongYouResultEntity<Object>>() {
            });
            if ("succ".equals(result.getMsg())) {
                log.info("回调成功，总用时：{}ms", System.currentTimeMillis() - start);
            } else {
                log.error("回调众油平台失败，失败原因：{}", result.getMsg());
//                throw new GlobalException(String.format("回调众油平台失败，失败原因：%s", result.getMsg()));
            }
        } else {
            log.error("回调众油平台返回结果格式异常");
        }
    }

    /**
     * 物流平台确认发车，运单状态进入“在途中”，对应提货单号下面，运单号及状态需要同步更新
     *
     * @param pickupOrderNo 众油平台唯一订单id（以提货单号为唯一ID）
     * @param transId       物流平台唯一运单id
     * @param strDate       日期例子： 2024-3-15 :12:24:35
     * @param nState        运单状态：比如1==在途中
     * @author fengxy
     * @date 2024/01/15 14:06
     **/
    public static void orderStateChange(String pickupOrderNo, String transId, String strDate, int nState) {
        long start = System.currentTimeMillis();
        log.info("运单【{}】确认发车，开始回调众油平台运单在途中状态", transId);
        Map<String, Object> params = MapUtil.newHashMap();
        params.put("pickupOrderNo", pickupOrderNo);
        params.put("transId", transId);
        params.put("strDate", strDate);
        params.put("nState", nState);
        log.info("请求参数：{}", JSONUtil.toJsonStr(params));
        String responseStr = HttpUtil.post(url + "/orderStateChange", params);
        log.info("响应结果：{}", responseStr);
        if (StrUtil.isBlank(responseStr)) {
            log.error("回调众油平台异常，响应结果为空");
//            throw new GlobalException("回调众油平台异常，响应结果为空");
        }
        if (JSONUtil.isTypeJSON(responseStr)) {
            ZhongYouResultEntity<Object> result = JSON.parseObject(responseStr, new TypeReference<ZhongYouResultEntity<Object>>() {
            });
            if ("succ".equals(result.getMsg())) {
                log.info("回调成功，总用时：{}ms", System.currentTimeMillis() - start);
            } else {
                log.error("回调众油平台失败，失败原因：{}", result.getMsg());
//                throw new GlobalException(String.format("回调众油平台失败，失败原因：%s", result.getMsg()));
            }
        } else {
            log.error("回调众油平台返回结果格式异常");
        }
    }

    /**
     * 物流平台通知众油平台已签收，并上传出库单（物流平台已签收触发）
     *
     * @param pickupOrderNo 众油平台唯一订单id（以提货单号为唯一ID）
     * @param transId       物流平台唯一运单id
     * @param strDate       完成时间
     * @param type1         出库单图片1类型："jpg"或 "png"
     * @param imagedata1    出库单图片1数据, 做base64处理
     * @param type2         出库单图片1类型："jpg"或 "png"
     * @param imagedata2    出库单图片1数据, 做base64处理
     * @author fengxy
     * @date 2024/01/15 14:06
     **/
    public static void orderFinish(String pickupOrderNo, String transId, String strDate, String type1, String imagedata1, String type2, String imagedata2) {
        long start = System.currentTimeMillis();
        log.info("运单【{}】已签收，开始回调众油平台并上传出库单", transId);
        Map<String, Object> params = MapUtil.newHashMap();
        params.put("pickupOrderNo", pickupOrderNo);
        params.put("transId", transId);
        params.put("strDate", strDate);
        params.put("type1", type1);
        params.put("imagedata1", imagedata1);
        params.put("type2", type2);
        params.put("imagedata2", imagedata2);
        log.info("请求参数：{}", JSONUtil.toJsonStr(params));
        String responseStr = HttpUtil.post(url + "/orderFinish", params);
        log.info("响应结果：{}", responseStr);
        if (StrUtil.isBlank(responseStr)) {
            log.error("回调众油平台异常，响应结果为空");
//            throw new GlobalException("回调众油平台异常，响应结果为空");
        }
        if (JSONUtil.isTypeJSON(responseStr)) {
            ZhongYouResultEntity<Object> result = JSON.parseObject(responseStr, new TypeReference<ZhongYouResultEntity<Object>>() {
            });
            if ("succ".equals(result.getMsg())) {
                log.info("回调成功，总用时：{}ms", System.currentTimeMillis() - start);
            } else {
                log.error("回调众油平台失败，失败原因：{}", result.getMsg());
//                throw new GlobalException(String.format("回调众油平台失败，失败原因：%s", result.getMsg()));
            }
        } else {
            log.error("回调众油平台返回结果格式异常");
        }
    }

}
